package com.ruoyi.system.async;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.system.domain.CrmCustomerInfo;
import com.ruoyi.system.domain.CrmCustomerUserInfo;
import com.ruoyi.system.mapper.CrmCustomerInfoMapper;
import com.ruoyi.system.service.ICrmCustomerInfoService;
import com.ruoyi.system.service.ICrmCustomerUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DataStatistics {

    @Autowired
    private ICrmCustomerUserService iCrmCustomerUserService;

    @Autowired
    private ModifyMasterData modifyMasterData;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CrmCustomerInfoMapper crmCustomerInfoMapper;

    @Autowired
    private ICrmCustomerInfoService crmCustomerInfoService;

    @Value("${python.getOutPython}")
    private String pyhtonUrl;

    /**
     * 多线程调用
     */
    private static Integer threadNumSta = 1;

    /**
     *  身份校验请求地址
     * @author NuanYang
     * @date 2023/5/27 10:34
     */

    private static String url = "https://cpadis.cpad.gov.cn:1443/cpad_par/app/observeHouse/checkIdentity?loginToken=&userId=&version=";

    /**
     *  获取验证码请求地址
     * @author NuanYang
     * @date 2023/5/27 10:34
     */
    private static final String verificationCodeUrl = "https://ecard.mva.gov.cn:18443/cert/pc/api/common/getCheckCode";

    /**
     * 查询优待证符合资格Url
     * @author NuanYang
     * @date 2023/5/27 10:34
     */
    private static final String searchUrl = "https://ecard.mva.gov.cn:18443/cert/pc/api/apply/qualificationCheck";

//    /**
//     * OCR接口验证码地址
//     */
//    private static final String ocrUrl="http://122.9.52.147/api/YmServer/customApi";

    private static final String ocrUrl="http://127.0.0.1:10111/sy";

    /**
     * 异步任务进行数据统计
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void dataStatistics(Long customerId, List<CrmCustomerUserInfo> crmCustomerUserInfos, String reptileType) throws ParseException, InterruptedException, IOException {
        log.info("开启进行公司id:" + customerId + "的数爬虫");
        if (reptileType.equals("import")) {
            CrmCustomerInfo crmCustomerInfo = crmCustomerInfoService.getById(customerId);
            List<CrmCustomerUserInfo> crmCustomerUserInfosnew=new ArrayList<>();
            for (CrmCustomerUserInfo crmCustomerUserInfo : crmCustomerUserInfos) {
//                if ("重庆市".equals(crmCustomerInfo.getProvinceName())){
//                    //单位缴费金额不为空且是重庆市下的数据时
//                    if (ObjectUtil.isNull(crmCustomerUserInfo.getDeptPaymentNumber())){
//                        log.info("重庆市内数据:"+crmCustomerUserInfo+"单位缴费金额为空剔除");
//                        continue;
//                    }else if (crmCustomerUserInfo.getDeptPaymentNumber()==0){
//                        log.info("重庆市内数据:"+crmCustomerUserInfo+"单位缴费金额等于0剔除");
//                        continue;
//                    }
//                }
                String feesDate = crmCustomerUserInfo.getFeesDate();
                int year;
                try {
                    year = Integer.parseInt(feesDate.substring(0, 4));
                }catch (Exception e){
                    log.error("数据:"+crmCustomerUserInfo+"对应费款所属期异常剔除数据");
                    continue;
                }
                if (year>=2019){
                    CrmCustomerUserInfo crmCustomerUserInfonew =new CrmCustomerUserInfo();
                    int genderByIdCard = getGenderByIdCard(crmCustomerUserInfo.getUserIdentityCardNumber());
                    int ageByIdCard = getAgeByIdCard(crmCustomerUserInfo.getUserIdentityCardNumber());
                    crmCustomerUserInfo.setUserGender(genderByIdCard);
                    crmCustomerUserInfo.setUserAge(ageByIdCard);
                    BeanUtils.copyProperties(crmCustomerUserInfo,crmCustomerUserInfonew);
                    crmCustomerUserInfosnew.add(crmCustomerUserInfonew);
                }else {
                    log.info("数据:"+crmCustomerUserInfo+"对应费款所属期小于2019年剔除");
                }
            }
            iCrmCustomerUserService.saveBatch(crmCustomerUserInfosnew);
        } else if (reptileType.equals("identity")) {
            List<CrmCustomerUserInfo> crmCustomerUserInfoList = checkIdentityList(customerId);
            iCrmCustomerUserService.updateBatchById(crmCustomerUserInfoList);
        } else if (reptileType.equals("unemployment")) {
            List<CrmCustomerUserInfo> crmCustomerUserInfoList = startScreeningList(customerId);
            iCrmCustomerUserService.updateBatchById(crmCustomerUserInfoList);
        }else if (reptileType.equals("retired")){
            List<CrmCustomerUserInfo> crmCustomerUserInfoList = retiredCrawlerList(customerId);
            iCrmCustomerUserService.updateBatchById(crmCustomerUserInfoList);
        } else if (reptileType.equals("all")) {
            List<CrmCustomerUserInfo> crmCustomerUserInfoList = allList(customerId);
            iCrmCustomerUserService.updateBatchById(crmCustomerUserInfoList);
        }else if (reptileType.equals("reptilallchick")){
            log.info("开启进行公司id:" + customerId + "的重新计算");
            this.reptilallchickData(customerId);
        }else {
            log.error("参数类型错误");
        }
        //确保事物提交后进行异步任务 异步进行数据计算
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @SneakyThrows
            @Override
            public void afterCommit() {
                modifyMasterData.startScreening(customerId, reptileType);
            }
        });

    }
    //重新计算前数据状态清空
    private void reptilallchickData(Long customerId){
        LambdaUpdateWrapper<CrmCustomerUserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CrmCustomerUserInfo::getIdentityCheckMsg,null)
                .set(CrmCustomerUserInfo::getIdentityCheckTime,null)
                .set(CrmCustomerUserInfo::getIdentityCheckDocument,null)
                .set(CrmCustomerUserInfo::getIdentityCheckDate,null)
                .set(CrmCustomerUserInfo::getRetiredCrawlerData,null)
                .set(CrmCustomerUserInfo::getRetiredCrawlerTime,null)
                .set(CrmCustomerUserInfo::getCrawlerCode,null)
                .set(CrmCustomerUserInfo::getCrawlerData,null)
                .set(CrmCustomerUserInfo::getCrawlerMsg,null)
                .eq(CrmCustomerUserInfo::getCustomerId,customerId);
        iCrmCustomerUserService.update(lambdaUpdateWrapper);

    }

    private List<CrmCustomerUserInfo> checkIdentityList(Long customerId){
        HashMap<String, CrmCustomerUserInfo> hashMap = new HashMap<>();
        //查询所有
        List<CrmCustomerUserInfo> customerUserInfoList = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNull("crawler_data"));
        List<CrmCustomerUserInfo> crmCustomerUserInfoList = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("crawler_data"));
        Map<String, List<CrmCustomerUserInfo>> stringListMap = crmCustomerUserInfoList.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));
        for (CrmCustomerUserInfo customerUserInfo : customerUserInfoList) {

            List<CrmCustomerUserInfo> customerUserInfos = stringListMap.get(customerUserInfo.getUserIdentityCardNumber());
            if (ObjectUtil.isNotNull(customerUserInfos) && customerUserInfos.size() > 0) {
                customerUserInfo.setCrawlerCode(customerUserInfos.get(0).getCrawlerCode());
                customerUserInfo.setCrawlerData(customerUserInfos.get(0).getCrawlerData());
                customerUserInfo.setCrawlerMsg(customerUserInfos.get(0).getCrawlerMsg());
            } else if (ObjectUtil.isNotNull(hashMap.get(customerUserInfo.getUserIdentityCardNumber()))) {
                CrmCustomerUserInfo crmCustomerUserInfo = hashMap.get(customerUserInfo.getUserIdentityCardNumber());
                customerUserInfo.setCrawlerCode(crmCustomerUserInfo.getCrawlerCode());
                customerUserInfo.setCrawlerData(crmCustomerUserInfo.getCrawlerData());
                customerUserInfo.setCrawlerMsg(crmCustomerUserInfo.getCrawlerMsg());
            } else {
                checkIdentity(customerUserInfo);
                hashMap.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
            }
        }
        return customerUserInfoList;
    }

    private List<CrmCustomerUserInfo> allList(Long customerId){
        HashMap<String, CrmCustomerUserInfo> hashMap = new HashMap<>();
        HashMap<String, CrmCustomerUserInfo> hashMapIdent = new HashMap<>();
        HashMap<String, CrmCustomerUserInfo> hashMapRetired=new HashMap<>();

        List<CrmCustomerUserInfo> customerUserInfos = crmCustomerInfoMapper.selectAll(customerId);
        List<CrmCustomerUserInfo> crmCustomerUserInfoList = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("crawler_data"));
        Map<String, List<CrmCustomerUserInfo>> stringListMap = crmCustomerUserInfoList.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));
        //失业筛查先关闭
//        List<CrmCustomerUserInfo> crmCustomerUserInfos = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("identity_check_msg"));
//        Map<String, List<CrmCustomerUserInfo>> stringListMapIdent = crmCustomerUserInfos.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));


        List<CrmCustomerUserInfo> crmCustomerUserInfoRetired = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("retired_crawler_data"));
        Map<String, List<CrmCustomerUserInfo>> stringListMapRetired= crmCustomerUserInfoRetired.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));


        for (CrmCustomerUserInfo customerUserInfo : customerUserInfos) {
            if (ObjectUtil.isNull(customerUserInfo.getCrawlerData())) {
                List<CrmCustomerUserInfo> crmCustomerUserInfos1 = stringListMap.get(customerUserInfo.getUserIdentityCardNumber());
                if (ObjectUtil.isNotNull(crmCustomerUserInfos1) && crmCustomerUserInfos1.size() > 0) {
                    customerUserInfo.setCrawlerCode(crmCustomerUserInfos1.get(0).getCrawlerCode());
                    customerUserInfo.setCrawlerData(crmCustomerUserInfos1.get(0).getCrawlerData());
                    customerUserInfo.setCrawlerMsg(crmCustomerUserInfos1.get(0).getCrawlerMsg());
                } else if (ObjectUtil.isNotNull(hashMap.get(customerUserInfo.getUserIdentityCardNumber()))) {
                    CrmCustomerUserInfo crmCustomerUserInfo = hashMap.get(customerUserInfo.getUserIdentityCardNumber());
                    customerUserInfo.setCrawlerCode(crmCustomerUserInfo.getCrawlerCode());
                    customerUserInfo.setCrawlerData(crmCustomerUserInfo.getCrawlerData());
                    customerUserInfo.setCrawlerMsg(crmCustomerUserInfo.getCrawlerMsg());
                } else {
                    checkIdentity(customerUserInfo);
                    hashMap.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
                }
            }
            //失业筛查先关闭
//            if (ObjectUtil.isNull(customerUserInfo.getIdentityCheckMsg())) {
//                List<CrmCustomerUserInfo> customerUserInfoList = stringListMapIdent.get(customerUserInfo.getUserIdentityCardNumber());
//                try {
//                    if (ObjectUtil.isNotNull(customerUserInfoList) && customerUserInfoList.size() > 0) {
//                        customerUserInfo.setIdentityCheckMsg(customerUserInfoList.get(0).getIdentityCheckMsg());
//                        customerUserInfo.setIdentityCheckTime(customerUserInfoList.get(0).getIdentityCheckTime());
//                        customerUserInfo.setIdentityCheckDocument(customerUserInfoList.get(0).getIdentityCheckDocument());
//                        customerUserInfo.setIdentityCheckDate(customerUserInfoList.get(0).getIdentityCheckDate());
//                    } else if (ObjectUtil.isNotNull(hashMapIdent.get(customerUserInfo.getUserIdentityCardNumber()))) {
//                        CrmCustomerUserInfo crmCustomerUserInfo = hashMapIdent.get(customerUserInfo.getUserIdentityCardNumber());
//                        customerUserInfo.setIdentityCheckMsg(crmCustomerUserInfo.getIdentityCheckMsg());
//                        customerUserInfo.setIdentityCheckTime(crmCustomerUserInfo.getIdentityCheckTime());
//                        customerUserInfo.setIdentityCheckDocument(crmCustomerUserInfo.getIdentityCheckDocument());
//                        customerUserInfo.setIdentityCheckDate(crmCustomerUserInfo.getIdentityCheckDate());
//                    } else {
//                        startScreeningPython(customerUserInfo);
//                        hashMapIdent.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
//                    }
//                } catch (Exception e) {
//                    log.error("失业筛查异常");
//                }
//            }
            if (ObjectUtil.isNull(customerUserInfo.getRetiredCrawlerData())){
                List<CrmCustomerUserInfo> customerUserInfoList = stringListMapRetired.get(customerUserInfo.getUserIdentityCardNumber());
                try {
                    if (ObjectUtil.isNotNull(customerUserInfoList) && customerUserInfoList.size() > 0) {
                        customerUserInfo.setRetiredCrawlerData(customerUserInfoList.get(0).getRetiredCrawlerData());
                        customerUserInfo.setRetiredCrawlerTime(customerUserInfoList.get(0).getRetiredCrawlerTime());
                    } else if (ObjectUtil.isNotNull(hashMapRetired.get(customerUserInfo.getUserIdentityCardNumber()))) {
                        CrmCustomerUserInfo crmCustomerUserInfo = hashMapRetired.get(customerUserInfo.getUserIdentityCardNumber());
                        customerUserInfo.setRetiredCrawlerData(crmCustomerUserInfo.getRetiredCrawlerData());
                        customerUserInfo.setRetiredCrawlerTime(crmCustomerUserInfo.getRetiredCrawlerTime());
                    } else {
                        searchCourtesyCardByNameAndidCard(customerUserInfo);
                        hashMapRetired.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
                    }
                } catch (Exception e) {
                    log.error("退役筛查异常");
                }
            }
        }
        return customerUserInfos;

    }

    /**
     * 失业
     *
     * @param
     */
    private List<CrmCustomerUserInfo> startScreeningList(Long customerId){
        HashMap<String, CrmCustomerUserInfo> hashMap = new HashMap<>();
        List<CrmCustomerUserInfo> customerUserInfos = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNull("identity_check_msg"));
        List<CrmCustomerUserInfo> crmCustomerUserInfoList = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("identity_check_msg"));
        Map<String, List<CrmCustomerUserInfo>> stringListMap = crmCustomerUserInfoList.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));
        for (CrmCustomerUserInfo customerUserInfo : customerUserInfos) {
            List<CrmCustomerUserInfo> customerUserInfoList = stringListMap.get(customerUserInfo.getUserIdentityCardNumber());
            try {
                if (ObjectUtil.isNotNull(customerUserInfoList) && customerUserInfoList.size() > 0) {
                    customerUserInfo.setIdentityCheckMsg(customerUserInfoList.get(0).getIdentityCheckMsg());
                    customerUserInfo.setIdentityCheckTime(customerUserInfoList.get(0).getIdentityCheckTime());
                    customerUserInfo.setIdentityCheckDocument(customerUserInfoList.get(0).getIdentityCheckDocument());
                    customerUserInfo.setIdentityCheckDate(customerUserInfoList.get(0).getIdentityCheckDate());
                } else if (ObjectUtil.isNotNull(hashMap.get(customerUserInfo.getUserIdentityCardNumber()))) {
                    CrmCustomerUserInfo crmCustomerUserInfo = hashMap.get(customerUserInfo.getUserIdentityCardNumber());
                    customerUserInfo.setIdentityCheckMsg(crmCustomerUserInfo.getIdentityCheckMsg());
                    customerUserInfo.setIdentityCheckTime(crmCustomerUserInfo.getIdentityCheckTime());
                    customerUserInfo.setIdentityCheckDocument(crmCustomerUserInfo.getIdentityCheckDocument());
                    customerUserInfo.setIdentityCheckDate(crmCustomerUserInfo.getIdentityCheckDate());
                } else {
                    startScreeningPython(customerUserInfo);
                    hashMap.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
                }
            } catch (Exception e) {
                log.error("执行失业爬虫脚本异常");
            }
        }
        return customerUserInfos;
    }

    /**
     * 退役
     *
     * @param
     */
    public List<CrmCustomerUserInfo> retiredCrawlerList(Long customerId){
        HashMap<String, CrmCustomerUserInfo> hashMap = new HashMap<>();
        List<CrmCustomerUserInfo> customerUserInfos = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNull("retired_crawler_data"));
        List<CrmCustomerUserInfo> crmCustomerUserInfoList = iCrmCustomerUserService.list(new QueryWrapper<CrmCustomerUserInfo>().eq("customer_id", customerId).isNotNull("retired_crawler_data"));
        Map<String, List<CrmCustomerUserInfo>> stringListMap = crmCustomerUserInfoList.stream().collect(Collectors.groupingBy(CrmCustomerUserInfo::getUserIdentityCardNumber));
        for (CrmCustomerUserInfo customerUserInfo : customerUserInfos) {
            List<CrmCustomerUserInfo> customerUserInfoList = stringListMap.get(customerUserInfo.getUserIdentityCardNumber());
            try {
                if (ObjectUtil.isNotNull(customerUserInfoList) && customerUserInfoList.size() > 0) {
                    customerUserInfo.setRetiredCrawlerData(customerUserInfoList.get(0).getRetiredCrawlerData());
                    customerUserInfo.setRetiredCrawlerTime(customerUserInfoList.get(0).getRetiredCrawlerTime());
                } else if (ObjectUtil.isNotNull(hashMap.get(customerUserInfo.getUserIdentityCardNumber()))) {
                    CrmCustomerUserInfo crmCustomerUserInfo = hashMap.get(customerUserInfo.getUserIdentityCardNumber());
                    customerUserInfo.setRetiredCrawlerData(crmCustomerUserInfo.getRetiredCrawlerData());
                    customerUserInfo.setRetiredCrawlerTime(crmCustomerUserInfo.getRetiredCrawlerTime());
                } else {
                    searchCourtesyCardByNameAndidCard(customerUserInfo);
                    hashMap.put(customerUserInfo.getUserIdentityCardNumber(), customerUserInfo);
                }
            } catch (Exception e) {
                log.error("执行退役爬虫异常");
            }
        }
        return customerUserInfos;
    }


    /**
     * 退役校验
     *
     * @param crmCustomerUserInfo
     */
    public void searchCourtesyCardByNameAndidCard(CrmCustomerUserInfo crmCustomerUserInfo){
        int i=0;
        while(true){
            String res = cn.hutool.http.HttpUtil.get(verificationCodeUrl);
            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(res);
            cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject(jsonObject.get("data"));
            cn.hutool.json.JSONObject object = new cn.hutool.json.JSONObject();
            object.put("sessionId",json.get("sessionId"));
            object.put("name",crmCustomerUserInfo.getUserName());
            object.put("idCardNumber",crmCustomerUserInfo.getUserIdentityCardNumber());
            // TODO 图片解析
            String s = this.generalBasic(Base64.getDecoder().decode(String.valueOf(json.get("base64")).substring(String.valueOf(json.get("base64")).indexOf(",") + 1)));
            object.put("code",s);
            Map<String,String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            String resp = Requests.post(searchUrl).headers(headers).jsonBody(object).connectTimeout(1000*60).send().readToText();
            cn.hutool.json.JSONObject respJson = new cn.hutool.json.JSONObject(resp);
            cn.hutool.json.JSONObject rjson = new cn.hutool.json.JSONObject(respJson.get("data"));
            if ("false".equals(rjson.get("success")) && "请输入正确的验证码".equals(rjson.get("info"))){
                log.info("校验优待证符合条件结果,姓名:"+crmCustomerUserInfo.getUserName()+";结果：验证码识别错误 重新查询");
                if (i>=10){
                    log.info("校验优待证符合条件结果,姓名:"+crmCustomerUserInfo.getUserName()+";结果：验证码识别错误,超过10次跳过该数据 ");
                    break;
                }else {
                    i++;
                    continue;
                }
            }else{
                if(ObjectUtil.isEmpty(rjson.get("provinceCode"))){
                    log.info("校验优待证符合条件结果,姓名:"+crmCustomerUserInfo.getUserName()+";结果：false");
                    crmCustomerUserInfo.setRetiredCrawlerData("false");
                    crmCustomerUserInfo.setRetiredCrawlerTime(new Date());
                    break;
                }else{
                    log.info("校验优待证符合条件结果,姓名:"+crmCustomerUserInfo.getUserName()+";结果：true");
                    crmCustomerUserInfo.setRetiredCrawlerData("true");
                    crmCustomerUserInfo.setRetiredCrawlerTime(new Date());
                    break;
                }
            }
        }

    }

    /**
     * 身份校验
     *
     * @param crmCustomerUserInfo
     */
    public void checkIdentity(CrmCustomerUserInfo crmCustomerUserInfo) {
        //身份校验
        try {
            MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            postParameters.add("name", crmCustomerUserInfo.getUserName());
            postParameters.add("idCode", crmCustomerUserInfo.getUserIdentityCardNumber());
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/x-www-form-urlencoded");
            HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
            String result = restTemplate.postForObject(url, r, String.class);
            JSONObject resultObj = JSON.parseObject(result);
            String code = resultObj.getString("code");
            String data = resultObj.getString("data");
            log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "身份校验结果是:" + data);
            String message = resultObj.getString("message");
            crmCustomerUserInfo.setCrawlerCode(code);
            crmCustomerUserInfo.setCrawlerData(data);
            crmCustomerUserInfo.setCrawlerMsg(message);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
    /**
     * JAVA调用python脚本
     * @param crmCustomerUserInfo
     * @throws IOException
     */
    public void startScreeningPython(CrmCustomerUserInfo crmCustomerUserInfo){
        try {
            String[] args1 = new String[]{"python", pyhtonUrl, crmCustomerUserInfo.getUserName(), crmCustomerUserInfo.getUserIdentityCardNumber()};//第二个为python脚本所在位置，后面的为所传参数（得是字符串类型）
            Process proc = Runtime.getRuntime().exec(args1);// 执行py文件

            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));//解决中文乱码，参数可传中文
            String line = null;
            String returnMessage =null;
            while ((line = in.readLine()) != null) {
                returnMessage=line;
                if (returnMessage!=null){
                    break;
                }
            }
            in.close();
            proc.waitFor();
            log.info(returnMessage);
            if ("false".equals(returnMessage)){
                log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "根据您输入的劳动者查询条件，没有查询到相关的就业失业登记者信息");
                crmCustomerUserInfo.setIdentityCheckMsg("false");
                crmCustomerUserInfo.setIdentityCheckTime(new Date());
            }else {
                String[] parts = returnMessage.split("\\|");
                String chickDocument =parts[0];
                String chickDate=parts[1];
                log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "查询到就业失业登记证编号为:"+chickDocument+",发证日期为:"+chickDate);
                Boolean aBoolean = dateComparisonExample("2020年01月01日",chickDate);
                if (aBoolean){
                    crmCustomerUserInfo.setIdentityCheckDocument(chickDocument);
                    crmCustomerUserInfo.setIdentityCheckDate(chickDate);
                    crmCustomerUserInfo.setIdentityCheckMsg("true");
                    crmCustomerUserInfo.setIdentityCheckTime(new Date());
                }else {
                    crmCustomerUserInfo.setIdentityCheckDocument(chickDocument);
                    crmCustomerUserInfo.setIdentityCheckDate(chickDate);
                    crmCustomerUserInfo.setIdentityCheckMsg("false");
                    crmCustomerUserInfo.setIdentityCheckTime(new Date());
                }
            }
        } catch (IOException | InterruptedException e) {
            log.error("执行python脚本失败"+crmCustomerUserInfo.getUserName()+","+crmCustomerUserInfo.getUserIdentityCardNumber());
        }
    }
    /**
     *
     * @throws IOException
     */
    public Boolean dateComparisonExample(String dateStr1,String dateStr2){

        // 创建日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        // 解析字符串并转换成 LocalDate 对象
        LocalDate date1 = LocalDate.parse(dateStr1, formatter);
        LocalDate date2 = LocalDate.parse(dateStr2, formatter);

        // 比较两个日期
        if (date1.isAfter(date2)) {
            System.out.println(dateStr1 + " 比 " + dateStr2 + " 更晚");
            return false;
        } else if (date1.isBefore(date2)) {
            System.out.println(dateStr1 + " 比 " + dateStr2 + " 更早");
            return true;
        } else {
            System.out.println(dateStr1 + " 和 " + dateStr2 + " 是同一天");
            return false;
        }
    }


    /**
     * JAVA调用失业 就业信息 存在问题 弃用 使用调用python脚本
     * @param crmCustomerUserInfo
     * @throws IOException
     */
//    public void startScreening(CrmCustomerUserInfo crmCustomerUserInfo) throws IOException {
//
//        ResponseEntity<Resource> result = restTemplate.getForEntity("http://jyjc.mohrss.gov.cn/verifyCode", Resource.class);
//        List<String> stringList = result.getHeaders().get("Set-Cookie");
//        org.springframework.core.io.Resource body = result.getBody();
//        if (body != null) {
//            InputStream inputStream = body.getInputStream();
//            // 转换成流
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int num = inputStream.read(buffer);
//            while (num != -1) {
//                baos.write(buffer, 0, num);
//                num = inputStream.read(buffer);
//            }
//            baos.flush();
//            byte[] data = baos.toByteArray();
//            String verifycode = this.generalBasic(data);
//            MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
//            postParameters.add("idcard", crmCustomerUserInfo.getUserIdentityCardNumber());
//            postParameters.add("pusername",URLEncoder.encode(crmCustomerUserInfo.getUserName(), "gbk"));
//            postParameters.add("verifycode", verifycode);
//            postParameters.add("ip","10.1.122.133");
//            HttpHeaders headers = new HttpHeaders();
//            headers.put(HttpHeaders.COOKIE, stringList);//将cookie存入头部
//            headers.add("Content-Type", "application/x-www-form-urlencoded");
//            HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
//            String postForObject = restTemplate.postForObject("http://jyjc.mohrss.gov.cn/public/jyinfo.do?method=query", r, String.class);
//            if (postForObject.contains("根据您输入的劳动者查询条件，没有查询到相关的就业失业登记者信息")) {
//                log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "根据您输入的劳动者查询条件，没有查询到相关的就业失业登记者信息");
//                crmCustomerUserInfo.setIdentityCheckMsg("false");
//                crmCustomerUserInfo.setIdentityCheckTime(new Date());
//            } else if (postForObject.contains("就业失业登记证编号")) {
//                log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "查询到就业失业登记证编号");
//                crmCustomerUserInfo.setIdentityCheckMsg("true");
//                crmCustomerUserInfo.setIdentityCheckTime(new Date());
//            } else {
//                log.info(crmCustomerUserInfo.getUserName() + "," + crmCustomerUserInfo.getUserIdentityCardNumber() + "接口错误，未包含判断信息");
//                crmCustomerUserInfo.setIdentityCheckTime(new Date());
//
//            }
//        }
//    }



    /**
     * ocr接口验证嘛解析
     *
     * @param imgData 图片byte
     * @return
     */
    public String generalBasic(byte[] imgData) {
        int i=0;
        //云网
        while (true){
            String url = ocrUrl;
            try {
                String encodeStr = Base64Util.encode(imgData);
                Map headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                String verify_type;
                verify_type = "9891";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("image", encodeStr);
                jsonObject.put("type", verify_type);
                jsonObject.put("token", "dXxMc9ejsCBnkjUcmHhCiY6XhFdDhBzBI-6uEjjFEio");
                String resp = Requests.post(url).headers(headers).jsonBody(jsonObject).connectTimeout(1000*100).send().readToText();
                JSONObject jsonObject1 = JSONObject.parseObject(resp);
                JSONObject jsonObject2 = jsonObject1.getJSONObject("data");
                String data = jsonObject2.getString("data");
                return data;
            } catch (Exception e) {
                if (i>=3){
                    log.error("该条数据获取云码验证码失败超过3次");
                    return "false";
                }else {
                    i++;
                    continue;
                }
            }
        }
//        return null;
        //百度
//        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
//        try {
//            String imgStr = Base64Util.encode(imgData);
//            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//            String param = "image=" + imgParam + "&language_type=ENG"+"&detect_direction=true";
//            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "24.11c5a0994f976fa8715e21bd05cc04da.2592000.1687759442.282335-34051246";
//            String result = com.ruoyi.system.async.HttpUtil.post(url, accessToken, param);
//            com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(result);
//            JSONArray wordsResult = jsonObject.getJSONArray("words_result");
//            com.alibaba.fastjson2.JSONObject wordsResultJSONObject = wordsResult.getJSONObject(0);
//            return wordsResultJSONObject.getString("words");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
    }


    /**
     * 百度ocr token 30天默认有效期：24.11c5a0994f976fa8715e21bd05cc04da.2592000.1687759442.282335-34051246
     * @author NuanYang
     * @date 2023/5/27 13:58
     */
    private String getToken(){
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        String clientId = "8OsMLvk8774mkdCI34kMyKCG";
        String clientSecret = "fEsai71SgajkGc1o9u3mPezHvz6fgyVr";
        String grantType = "client_credentials";

        String response = cn.hutool.http.HttpUtil.createPost(url)
                .form("client_id", clientId)
                .form("client_secret", clientSecret)
                .form("grant_type", grantType)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .execute()
                .body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(response);
        Object access_token = jsonObject.get("access_token");
        return String.valueOf(access_token);
    }


    /**
     * 根据身份证号码获取年龄
     *
     * @param idCard 身份证号码
     * @return 年龄
     */
    public static int getAgeByIdCard(String idCard) {
        int age;
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DAY_OF_MONTH);

        if (idCard.length() == 18) {
            int year = Integer.parseInt(idCard.substring(6, 10));
            int month = Integer.parseInt(idCard.substring(10, 12));
            int day = Integer.parseInt(idCard.substring(12, 14));
            if (year < yearNow) {
                age = yearNow - year;
                if (month > monthNow) {
                    age--;
                } else if (month == monthNow) {
                    if (day > dayNow) {
                        age--;
                    }
                }
            } else {
                age = 0;
            }

        } else if (idCard.length() == 15) {
            int year = Integer.parseInt(idCard.substring(6, 8)) + 1900;
            int month = Integer.parseInt(idCard.substring(8, 10));
            int day = Integer.parseInt(idCard.substring(10, 12));
            if (year < yearNow) {
                age = yearNow - year;
                if (month > monthNow) {
                    age--;
                } else if (month == monthNow) {
                    if (day > dayNow) {
                        age--;
                    }
                }
            } else {
                age = 0;
            }
        } else {
            age = 0;
        }
        return age;
    }



    /**
     * 根据身份证号码获取性别
     *
     * @param idCard 身份证号码
     * @return 性别（1-男，2-女）
     */
    public static int getGenderByIdCard(String idCard) {
        int gender = 0;
        if (idCard.length() == 18) {
            int index = Integer.parseInt(idCard.substring(16, 17));
            if (index % 2 == 0) {
                gender = 2;
            } else {
                gender = 1;
            }
        } else if (idCard.length() == 15) {
            int index = Integer.parseInt(idCard.substring(14, 15));
            if (index % 2 == 0) {
                gender = 2;
            } else {
                gender = 1;
            }
        }
        return gender;
    }



}
